package com.chuangjian.hire.sms.service.impl;


import com.chuangjian.hire.captcha.CaptchaClient;
import com.chuangjian.hire.captcha.bean.CaptchaBean;
import com.chuangjian.hire.captcha.service.ImageTypeEnum;
import com.chuangjian.hire.captcha.utils.Base64Util;
import com.chuangjian.hire.common.exceptionEnum.ApiExceptionEnum;
import com.chuangjian.hire.common.exption.ApiException;
import com.chuangjian.hire.sms.service.ImageCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 获取图片验证码
 */
@Slf4j
@Service
public class ImageCodeServiceImpl implements ImageCodeService {


    private static final String IMAGE_CODE_PREFIX = "image_code_prefix_";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public byte[] getImage(String imageKey) {
        if (StringUtils.isBlank(imageKey)) {
            throw new ApiException(ApiExceptionEnum.NO_PARAM_ERROR);
        }
        try {
            CaptchaClient multivariateOperationCaptchaClient = CaptchaClient.create()
//                    .captchaStrategy(new MultivariateOperationCaptchaStrategy())
                    .transform(true)
                    .imageType(ImageTypeEnum.PNG)
//                    .lineNum(0)
                    .number(4)
                    .build();
            CaptchaBean generate = multivariateOperationCaptchaClient.generate();
            byte[] image = Base64Util.decode(generate.getBase64());
            redisTemplate.opsForValue().set(getKey(imageKey), generate.getResult(), 120, TimeUnit.SECONDS);
            return image;
        } catch (Exception e) {
            log.error("验证码生成错误:", e);
        }
        return null;
    }

    @Override
    public Boolean validateImageCode(String imageKey, String imageCode) {
        if (!validateImageKey(imageKey, imageCode)) {
            throw new ApiException(ApiExceptionEnum.VERIFY_CODE_ERROR);
        }
        redisTemplate.delete(getKey(imageKey));
        return true;
    }

    @Override
    public Boolean validateImageCodeNoException(String imageKey, String imageCode) {
        Boolean result = validateImageKey(imageKey, imageCode);
        redisTemplate.delete(getKey(imageKey));
        return result;
    }


    private Boolean validateImageKey(String imageKey, String imageCode) {
        if (StringUtils.isBlank(imageKey) || StringUtils.isBlank(imageCode)) {
            throw new ApiException(ApiExceptionEnum.NO_PARAM_ERROR);
        }
        return imageCode.equalsIgnoreCase(redisTemplate.opsForValue().get(getKey(imageKey)));
    }

    private String getKey(String imageKey) {
        return IMAGE_CODE_PREFIX.concat(imageKey);
    }

}
